﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ChatGPT3._5_Turbo
{
    public partial class RegisterForm : Form
    {
        public RegisterForm()
        {
            InitializeComponent();
        }
        public event EventHandler? StartSave;

        public string? IP
        {
            get;set;
        }
        public string? Port
        {
            get; set;
        }
        public bool IsSSL
        {
            get; set;
        }
        public string? Password2
        {
            get
            {
                return txt_Password2.Text;
            }
            set
            {
                txt_Password2.Text = value;
            }
        }

        public string? UserName
        {
            get
            {
                return txt_UserName.Text;
            }
            set
            {
                txt_UserName.Text = value;
            }
        }

        public string? Password
        {
            get
            {
                return txt_Password.Text;
            }
            set
            {
                txt_Password.Text = value;
            }
        }
        public string Mail
        {
            get
            {
                return txt_Mail.Text;
            }
            set
            {
                txt_Mail.Text = value;
            }
        }
        public string Phone
        {
            get
            {
                return txt_Phone.Text;
            }
            set
            {
                txt_Phone.Text = value;
            }
        }

        public async Task<string> HandleGetApi(string APIName)
        {
            string responseContent = string.Empty;
            try
            {
                if (IsSSL)
                {
                    using (HttpClient _httpClient = new HttpClient())
                    {
                        var apiUrl = "https://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.GetAsync(apiUrl);
                        responseContent = await response.Content.ReadAsStringAsync();
                        //return responseContent;
                    }
                }
                else
                {
                    var httpClientHandler = new HttpClientHandler();
                    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                    using (HttpClient _httpClient = new HttpClient(httpClientHandler))
                    {
                        var apiUrl = "http://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.GetAsync(apiUrl);
                        responseContent = await response.Content.ReadAsStringAsync();
                        //return responseContent;
                    }
                }

                using (HttpClient _httpClient = new HttpClient())
                {

                    string http = "http";
                    if (IsSSL)
                        http = "https";
                    var apiUrl = http + "://" + IP + ":" + Port + "/" + APIName;
                    var response = await _httpClient.GetAsync(apiUrl);
                    responseContent = await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                responseContent = "网络连接失败，请确认连接参数是否正确";
            }
            return responseContent;
        }
        public async Task<string> HandlePostApi(string APIName, string[] parameters)
        {
            string responseContent = string.Empty;
            try
            {
                List<string> data = new List<string>();
                for (int i = 0; i < parameters.Length; i++)
                    data.Add(parameters[i]);
                string json = YZZ.工应.WebAPI.ListToJson(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                if (IsSSL)
                {
                    using (HttpClient _httpClient = new HttpClient())
                    {
                        var apiUrl = "https://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.PostAsync(apiUrl, content);
                        responseContent = await response.Content.ReadAsStringAsync();
                        //return responseContent;
                    }
                }
                else
                {
                    var httpClientHandler = new HttpClientHandler();
                    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                    using (HttpClient _httpClient = new HttpClient(httpClientHandler))
                    {
                        var apiUrl = "http://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.PostAsync(apiUrl, content);
                        responseContent = await response.Content.ReadAsStringAsync();
                        //return responseContent;
                    }
                }

            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                responseContent = "网络连接失败，请确认连接参数是否正确";
            }
            return responseContent;
        }

        private void btn_Register_Click(object sender, EventArgs e)
        {
      
            try
            {
                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork += Login_DoWork;
                bg.RunWorkerCompleted += Login_RunWorkerCompleted;
                bg.RunWorkerAsync();
                this.Enabled = false;
            }
            catch (Exception ex)
            {
                YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                this.Enabled = true;
            }
        }

        private async void Login_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
        {

            try
            {
                string Result = YZZ.工.转.ToString(e.Result);
                if (string.IsNullOrEmpty(Result))
                {
                    #region 尝试连接，成功则保存
                    string Reponse = await HandlePostApi("Register", new string[] { UserName, YZZ.工应.WebAPI.getMd5(Password), Mail, Phone });
                    if (Reponse.Contains("成功"))
                    {
                        MessageBox.Show("注册成功");
                        this.DialogResult = DialogResult.OK;
                        return;
                    }
                    Result = Reponse;

                    #endregion
                }


                MessageBox.Show(Result);

            }
            catch (Exception ex)
            {
                YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                MessageBox.Show("注册失败");
            }

            this.Enabled = true;


        }

        private void Login_DoWork(object? sender, DoWorkEventArgs e)
        {
            try
            {
                
                #region 检查用户名密码合法性
                if (string.IsNullOrEmpty(UserName))
                {
                    e.Result = "请填写用户名";
                    return;
                }

                if (string.IsNullOrEmpty(Password))
                {
                    e.Result = "请填写密码";
                    return;
                }
                if (Password != Password2)
                {
                    e.Result = "两次输入的密码不一致";
                    return;
                }
                if (string.IsNullOrEmpty(Mail))
                {
                    e.Result = "请填写邮箱地址";
                    return;
                }

                if (string.IsNullOrEmpty(Phone))
                {
                    e.Result = "请填写手机/QQ号码";
                    return;
                }
                #endregion

            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                

            }

        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
